#include <QLabel>
#include <QDesktopServices>
#include <QMessageBox>
#include <QTableWidgetItem>

#include <gui/mainwindow.h>
#include <gui/sponsorwindow.h>
#include <gui/taskwindow.h>
#include <layer/tmslayer.h>
namespace EasyGIS {

QString
MainWindow::tutorialUrl() {
  return QString{R"(https://gitee.com/qizr_admin/easygis)"};
}

QString
MainWindow::srcUrl() {
  return QString{R"(https://gitee.com/qizr_admin/easygis)"};
}

QHash<QString, MapLayer *>MainWindow::mMaps{};

MainWindow::MainWindow(QWidget *parent)
    : mUi(new Ui::MainWindow),
      mMapConvas(new MapCanvas),
      mScaleText(new QLineEdit),
      mScaleLabel(new QLabel),
      mCenterText(new QLineEdit),
      mCenterLabel(new QLabel),
      mZoomText(new QLineEdit),
      mZoomLabel(new QLabel),
      mMapActionGroup(new QActionGroup(dynamic_cast<QObject *>(this))),
      mSetLeftTop(true),
      mLayerList(),
      mLeftTop(),
      mRightBottom() {
  mUi->setupUi(dynamic_cast<QMainWindow *>(this));
  setupWindow();
  setupTaskWindow();
  setupLayers();
  setupStatusBar();
  setupActions();

  mUi->panAction->trigger();
  mUi->layerList->setCurrentItem(mLayerList.first());
}

MainWindow::~MainWindow() {
  delete mUi;
  delete mMapConvas;
  delete mScaleText;
  delete mScaleLabel;
  delete mCenterText;
  delete mCenterLabel;
}

void
MainWindow::setupTaskWindow() {
  mUi->taskTable->setColumnCount(5);
  mUi->taskTable->setHorizontalHeaderLabels(QStringList{
      "名称", "范围", "zoom值", "数据源", "进度"
  });
  mUi->taskTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
}

void
MainWindow::setupActions() {
  mMapActionGroup->addAction(mUi->panAction);
  mMapActionGroup->addAction(mUi->zoomInAction);
  mMapActionGroup->addAction(mUi->zoomOutAction);
  mMapActionGroup->addAction(mUi->selectAction);

  mUi->selectAction->setEnabled(false);

  QObject::connect(mUi->panAction, &QAction::triggered, this, &MainWindow::panHandle);
  QObject::connect(mUi->zoomInAction, &QAction::triggered, this, &MainWindow::zoomInHandle);
  QObject::connect(mUi->zoomOutAction, &QAction::triggered, this, &MainWindow::zoomOutHandle);
  QObject::connect(mUi->tutorialAction, &QAction::triggered, this, &MainWindow::tutorialHanle);
  QObject::connect(mUi->srcAction, &QAction::triggered, this, &MainWindow::srcHandle);
  QObject::connect(mUi->refreshAction, &QAction::triggered, this, &MainWindow::refreshHandle);
  QObject::connect(mUi->sponsorAction, &QAction::triggered, this, &MainWindow::sponsorHandle);
  QObject::connect(mUi->selectAction, &QAction::triggered, this, &MainWindow::selectHandle);
  QObject::connect(mUi->downloadAction, &QAction::triggered, this, &MainWindow::createDownloadTask);
  QObject::connect(mUi->drawlineAction, &QAction::triggered, this, &MainWindow::drawlineHandle);
}

void MainWindow::setupWindow() {
  mUi->mapCanvasLayout->addWidget(mMapConvas);
  setFixedSize(size());
  setWindowFlags(windowFlags() & ~Qt::WindowMaximizeButtonHint);

  QObject::connect(mMapConvas, &MapCanvas::zoomChanged, this, &MainWindow::zoomChangedHandle);
  QObject::connect(mMapConvas, &MapCanvas::clicked, this, &MainWindow::clickedHandle);
  QObject::connect(mMapConvas, &MapCanvas::mapCenterChanged, this, &MainWindow::centerChangedHandle);
  QObject::connect(mUi->layerList, &QListWidget::currentItemChanged, this, &MainWindow::layerChanged);
  QObject::connect(mUi->leftTopBtn, &QPushButton::clicked, this, &MainWindow::leftTopClickedHandle);
  QObject::connect(mUi->rightBottomBtn, &QPushButton::clicked, this, &MainWindow::rightBottomClickedHandle);
}

void MainWindow::setupStatusBar() {
  /// 比例尺
  mScaleLabel->setText("比例尺");
  mScaleText->setText(QString("1cm : %1m").arg(mMapConvas->scale()));
  mScaleText->setFixedWidth(150);
  mScaleText->setReadOnly(true);
  mUi->statusbar->addWidget(mScaleLabel);
  mUi->statusbar->addWidget(mScaleText);

  /// 空白间隔
  mUi->statusbar->addWidget(spacerWiget(30));

  /// zoom值
  mZoomLabel->setText("Zoom值=>");
  mZoomText->setText(QString("%1").arg(mMapConvas->zoomValue()));
  mZoomText->setFixedWidth(80);
  mZoomText->setReadOnly(true);
  mUi->statusbar->addWidget(mZoomLabel);
  mUi->statusbar->addWidget(mZoomText);

  /// 空白间隔
  mUi->statusbar->addWidget(spacerWiget(30));

  /// 视图中心坐标
  mCenterLabel->setText("视图中心坐标=>");
  PointXY center = mMapConvas->mapCenter();
  mCenterText->setText(QString("lon:%1, lat:%2").arg(center.x()).arg(center.y()));
  mCenterText->setFixedWidth(300);
  mCenterText->setReadOnly(true);
  mUi->statusbar->addWidget(mCenterLabel);
  mUi->statusbar->addWidget(mCenterText);
}

void MainWindow::setupLayers() {
  initMaps();
  auto i = mMaps.constBegin();
  for (; i != mMaps.constEnd(); ++i) {
    mLayerList.append(new QListWidgetItem(i.key(), mUi->layerList));
  }
}

void
MainWindow::initMaps() {
  if (mMaps.isEmpty()) {
    mMaps = QHash<QString, MapLayer *>{
        {"Openstreet地图", new TmsLayer(OSTNormalMap, "ostnormalmap", mMapConvas)},
        {"高德地图", new TmsLayer(GaodeNormapMap, "gaodenormalmap", mMapConvas)}
    };
  }
}

QWidget *MainWindow::spacerWiget(int width) const {
  auto spacer = new QWidget{};
  spacer->setHidden(true);
  spacer->setVisible(true);
  spacer->setFixedWidth(width);

  return spacer;
}

void
MainWindow::panHandle(bool checked) {
  mMapConvas->selectTool(QString{"pan_tool"});
}

void
MainWindow::zoomInHandle(bool checked) {
  mMapConvas->selectTool(QString{"zoomin_tool"});
}

void
MainWindow::zoomOutHandle(bool checked) {
    mMapConvas->selectTool(QString{"zoomout_tool"});
}

void MainWindow::drawlineHandle(bool checked)
{
    mMapConvas->selectTool("drawline_tool");
}

void
MainWindow::tutorialHanle(bool checked) {
  if (!QDesktopServices::openUrl(tutorialUrl())) {
    QMessageBox::critical(dynamic_cast<QWidget *>(this), "异常", "未能打开系统浏览器");
  }
}

void
MainWindow::srcHandle(bool checked) {
  if (!QDesktopServices::openUrl(srcUrl())) {
    QMessageBox::critical(dynamic_cast<QWidget *>(this), "异常", "未能打开系统浏览器");
  }
}

void
MainWindow::sponsorHandle(bool checked) {
  auto *window = new SponsorWindow(dynamic_cast<QWidget *>(this));
  window->exec();
  window->deleteLater();
}

void
MainWindow::refreshHandle(bool checked) {
  mMapConvas->refreshMap();
}

void
MainWindow::selectHandle(bool checked) {
  mMapConvas->selectTool(QString{"select_tool"});
}

void
MainWindow::centerChangedHandle(EasyGIS::PointXY pos) {
  mCenterText->setText(QString("lon:%1, lat:%2").arg(pos.x()).arg(pos.y()));
}

void
MainWindow::zoomChangedHandle(int zoom) {
  mZoomText->setText(QString("%1").arg(zoom));
  mScaleText->setText(QString("1cm:%1m").arg(this->mMapConvas->scale()));
}

void
MainWindow::clickedHandle(EasyGIS::PointXY pos) {
  QString posText = QString("%1, %2").arg(pos.x()).arg(pos.y());
  if (mSetLeftTop) {
    mUi->leftTopText->setText(posText);
    mLeftTop = pos;
  } else {
    mUi->rightBottomText->setText(posText);
    mRightBottom = pos;
  }
}

void
MainWindow::leftTopClickedHandle() {
  mSetLeftTop = true;
  mUi->selectAction->trigger();
}

void
MainWindow::rightBottomClickedHandle() {
  mSetLeftTop = false;
  mUi->selectAction->trigger();
}

void
MainWindow::layerChanged(QListWidgetItem *current, QListWidgetItem *previous) {
  auto mapName = current->text();
  if (!mMaps.contains(mapName)) {
    qDebug() << mapName << "不支持";
    return;
  }

  auto layer = mMaps.value(mapName);
  auto i = mMaps.begin();
  for (; i != mMaps.end(); ++i) {
    if (i.key() == mapName) {
      i.value()->setVisiblity(true);
      qDebug() << i.key() << i.value()->isVisible();
      continue;
    }

    i.value()->setVisiblity(false);
  }

  mMapConvas->addLayer(layer);
  mMapConvas->setCurrentLayer(layer->id());
  mMapConvas->refreshMap();

  zoomChangedHandle(mMapConvas->zoomValue());
  centerChangedHandle(mMapConvas->mapCenter());
}

void
MainWindow::createDownloadTask() {
  auto taskWindow = new TaskWindow(dynamic_cast<QWidget *>(this));
  taskWindow->exec();
  taskWindow->deleteLater();
}

void
MainWindow::changeTaskTable(int row, int col, QString text) {
  mUi->taskTable->takeItem(row, col);
  mUi->taskTable->setItem(row, col, new QTableWidgetItem(text));
}


void MainWindow::on_drawArea_triggered()
{
     mMapConvas->selectTool("drawarea_tool");
}


void MainWindow::on_addPlaneaction_triggered()
{
    mMapConvas->selectTool("addplane_tool");
}

}

